package app.server.project.core.httpauth;

import app.server.project.core.constants.Def;
import app.server.project.core.exception.SysError;
import app.server.project.core.token.TokenCache;
import app.server.project.core.util.AssertUtil;
import cn.hutool.core.util.StrUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Objects;

@Component
@Slf4j
public class AuthInterceptor implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            if (Objects.isNull(handlerMethod.getMethodAnnotation(UnAuth.class))) {
                var userId = request.getHeader(Def.UserId);
                if (StrUtil.isBlank(userId)) {
                    log.info("header 没有带UserId");
                }
                AssertUtil.isTrue(StrUtil.isNotBlank(userId), SysError.UserId);
                var token = request.getHeader(Def.Token);
                if (StrUtil.isBlank(token)) {
                    log.info("header 没有带token");
                }
                var flag = TokenCache.chkToken(Long.parseLong(userId), token);
                AssertUtil.isTrue(flag, SysError.ErrorToken);
            }
            return true;
        }
        return false;
    }
}
